//
//  UIImage+Addtions.swift
//  Pods
//
//  Created by Max on 2020/5/18.
//

import UIKit
import Kingfisher

extension Extensive where Base: UIImage {
    
    public static func imageWithColor(_ color: UIColor) -> UIImage? {
        let rect = CGRect(origin: .zero, size: CGSize(width: 1, height: 1))
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else {
            return nil
        }
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return theImage
    }
    
}

public extension UIImage {
    /// 生成高斯模糊图
    func gaussianBlur(sigma: CGFloat) -> UIImage? {
        guard let beginImage = CIImage(image: self) else { return nil }
        let blurFilter = CIFilter(name: "CIGaussianBlur")!
        blurFilter.setValue(beginImage, forKey: kCIInputImageKey)
        blurFilter.setValue(sigma, forKey: kCIInputRadiusKey)
        
        //生成模糊图片
        let context = CIContext(options: nil)
        let rect = CGRectInset(beginImage.extent, sigma*2, sigma*2)
        guard let cgImage = blurFilter.value(forKey: kCIOutputImageKey) as? CIImage, let result = context.createCGImage(cgImage, from: rect) else {
            return nil
        }
        return UIImage(cgImage: result)
    }
    
    // 压缩图片到指定尺寸
    func compressImageSize(to size: CGSize) -> UIImage {
        let targetSize = size
        if self.size.width > targetSize.width || self.size.height > targetSize.height {
            return kf.resize(to: targetSize)
        }
        return self
    }
    
    // 颜色生成渐变图
    class func gradientImage(colors: [CGColor],
                             locations: [NSNumber]? = nil,
                             size: CGSize,
                             startPoint: CGPoint = CGPoint(x: 0, y: 0),
                             endPoint: CGPoint = CGPoint(x: 1, y: 0)) -> UIImage {
        
        UIGraphicsBeginImageContext(size)
        
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
        
        let gradLayer = CAGradientLayer()
        gradLayer.frame = CGRectMake(0, 0, size.width, size.height)
        gradLayer.startPoint = startPoint
        gradLayer.endPoint = endPoint
        
        gradLayer.locations = locations
        gradLayer.colors = colors
        
        gradLayer.render(in: context)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        return image ?? UIImage()
    }
}
